package com.wutma.friend.manager;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wutma.common.core.constants.CacheConstants;
import com.wutma.common.redis.service.RedisService;
import com.wutma.friend.domain.user.entity.User;
import com.wutma.friend.domain.user.vo.UserVO;
import com.wutma.friend.mapper.user.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class UserCacheManager {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisService redisService;

    public UserVO getUserById(Long userId) {

        String userKey = getUserKey(userId);
        UserVO userVO = redisService.getCacheObject(userKey, UserVO.class);
        if (userVO != null) {
            // 缓存中能查询到数据
            redisService.expire(userKey, CacheConstants.USER_DETAIL_EXPIRE_TIME, TimeUnit.MINUTES);
            return userVO;
        }
        // 缓存中查询不到数据，从数据库中查询
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().select(
                User::getUserId,
                User::getNickName,
                User::getHeadImage,
                User::getSex,
                User::getEmail,
                User::getPhone,
                User::getWechat,
                User::getIntroduce,
                User::getSchoolName,
                User::getMajorName,
                User::getStatus
        ).eq(User::getUserId, userId));
        if (user == null) {
            return null;
        }
        // 数据库中能查询到数据，刷新缓存并返回结果
        return refreshCache(user);
    }

    public UserVO refreshCache(User user) {
        String userKey = getUserKey(user.getUserId());
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(user, userVO);
        redisService.setCacheObject(userKey, userVO, CacheConstants.USER_DETAIL_EXPIRE_TIME, TimeUnit.MINUTES);
        return userVO;
    }

    private String getUserKey(Long userId) {

        return CacheConstants.USER_DETAIL + userId;

    }
}
